/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Platform,
    InteractionManager
} from 'react-native';
import { SwipeListView,SwipeRow } from 'react-native-swipe-list-view';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import PublicTask from './PublicTask';
import shopService from '../lib/services/shopService';
import StorageUser from '../lib/plugins/StorageUser';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class ActiveList extends Component{
    constructor(props) {
        super(props);
        this.rowList = [];
        this.userId = '';
        this.shopId = '';
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            dataSource:ds.cloneWithRows(this.rowList),
            token:this.props.navigation.state.params.token,
        };
        
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.userId){
                    $this.userId = data.userId;
                }
                if(data.shopId){
                    $this.shopId = data.shopId;
                }
                InteractionManager.runAfterInteractions(() => {
                    $this.getListData();
                });
            }).catch(err=> {
                console.log(err)
            }); 
        
    }

    renderListItem(rowData,sectionID,rowId){
        var timeText = '';
        var  endTime= new Date(rowData.end_time*1000);
        var startTime = new Date(rowData.start_time*1000);
        timeText = startTime.getFullYear()+'.'+(startTime.getMonth()>8?(startTime.getMonth()+1):('0'+(startTime.getMonth()+1)))+'.'+(startTime.getDate()>9?startTime.getDate():('0'+startTime.getDate()))+'-'+endTime.getFullYear()+'.'+(endTime.getMonth()>8?(endTime.getMonth()+1):('0'+(endTime.getMonth()+1)))+'.'+(endTime.getDate()>9?endTime.getDate():('0'+endTime.getDate()));
        return(
            <View>
                <SwipeRow
                    closeOnRowPress={true}
                    rightOpenValue={-120} 
                    disableRightSwipe={true}>
                    <View style={{flex:1,flexDirection:'row',justifyContent:'flex-end'}}>
                        <TouchableOpacity style={{backgroundColor:'#ccc',width:60,alignItems:'center',justifyContent:'center'}} onPress={()=>this.goEditActive(rowData)}>
                            <View>
                                <Text style={{color:'#fff',fontSize:16}}>编辑</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={()=>this.deleteActive(rowData,rowId)} style={{backgroundColor:'#ff0000',width:60,alignItems:'center',justifyContent:'center'}}>
                            <View>
                                <Text style={{color:'#fff',fontSize:16}}>删除</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View>
                        <ActiveItem activeTitle={rowData.title} num={rowData.person_num} activeTime={timeText} activeContent={rowData.content} icon={{uri:'http://peita.oss-cn-beijing.aliyuncs.com/'+rowData.list_img}}/>
                    </View>
                </SwipeRow>
            </View>
        )
    }

    render(){
        return (
            <View style={styles.container}>
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={'活动列表'} 
                    leftPress={()=>this.goBack()}
                    rightText={'+'}
                    rightTextStyle={{color:'#fff',fontSize:24}}
                    rightTextPress={()=>this.goPublicTask()}/>
                <SwipeListView
                    dataSource={this.state.dataSource}
                    enableEmptySections={true}
                    renderRow={(rowData,sectionID,rowId) => this.renderListItem(rowData,sectionID,rowId)}/>   
            </View>
        )

    }
    // 返回
    goBack(){
        this.props.navigation.goBack();
    }
    // 跳转到发布任务页面
    goPublicTask(){
        var $this = this;
        const {navigate } = this.props.navigation;
        navigate('PublicTask',{upData:()=>{
            $this.getListData();
        }})
    }
    goEditActive(data){
        const {navigate } = this.props.navigation;
        navigate('EditActive',{activeId:data.ac_id})
    }
    getListData(){
        var $this = this;
        shopService.userActivityLists(function(data){
            if(data.code==10000){
                $this.rowList = data.data;
                $this.setState({
                    dataSource:$this.state.dataSource.cloneWithRows($this.rowList)
                })
            }
        },$this.userId,$this.shopId,$this.state.token)
    }
    // 删除活动
    deleteActive(rowData,rowId){
        var $this = this;
        shopService.activityIdDel(function(data){
            if(data.code==10000){
                $this.rowList.splice(rowId,1);
                $this.rowList = JSON.parse(JSON.stringify($this.rowList))
                $this.setState({
                    dataSource:$this.state.dataSource.cloneWithRows($this.rowList)
                })
            }
        },rowData.ac_id,$this.state.token)
    }

}

class ActiveItem extends Component{
    render(){
        return(
            <View style={styles.activeItemBox}>
                <View>
                    <ImageWrapper width={80} height={80} icon={this.props.icon}/>
                </View>
                <View style={{flex:1,marginLeft:10}}>
                    <View style={{flex:1,flexDirection:'row',justifyContent:'space-between',alignItems:'center'}}>
                        <Text style={{color:'#333',fontSize:18}}>{this.props.activeTitle}</Text>
                        <Text style={{fontSize:12}}>人数 : {this.props.num}</Text>
                    </View>
                    <View style={{flex:1,justifyContent:'center'}}>
                        <Text style={{fontSize:12}}>活动时间 : {this.props.activeTime}</Text>
                    </View>
                    <View style={{flex:1,justifyContent:'center'}}>
                        <Text numberOfLines={1} style={{fontSize:12}}>{this.props.activeContent}</Text>
                    </View>
                </View>
            </View>
        )
    }
}


const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },

        }),
    }, 
    activeItemBox:{
        flexDirection:'row',
        padding:10,
        alignItems:'center',
        backgroundColor:'#fff',
        borderBottomWidth:1,
        borderBottomColor:'#ccc'
    }
    
});